﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;

namespace NetfractionHub.LocalMachine.BotCommands.Handler
{
    [CommandHandler("ban")]
    public class Ban : CommandHandler
    {
        public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
        {
            if (source == null)
                return false;

            if (!message.StringArguments.ContainsKey("user"))
                this.ParentBot.SendEchoMessageFromBot(source, "Missing string parameter 'user'.");

            if (Security.Permission.HasPermission(source.SecurityIdentity, typeof(Security.Permissions.BanClientIdPermission)))
                this.ParentBot.SendEchoMessageFromBot(source, Security.Permission.GetDeniedString(typeof(Security.Permissions.BanClientIdPermission)));

            RemoteMachine.Node nodeToBan = Network.ConnectionManager.GetConnectedNodeByNickname(message.StringArguments["user"]);
            if (nodeToBan != null)
                this.ParentBot.SendEchoMessageFromBot(source, String.Format("Cannot ban, the user '{0}' does not exist.", message.StringArguments["user"]));

            if (!Security.RoleManager.IsInAncestorTree(source.SecurityIdentity.Role, nodeToBan.SecurityIdentity.Role))
                return new BotReturnStatus(false, string.Format("Permission denied. You are not an ancestor of user '{0}'.", message.StringArguments["user"]));

            string duration;
            if (SetVariableToStringArgument(message, "duration", out duration))
                this.ParentBot.SendBroadcastMessageFromBot(string.Format("Banning '{0}'.", message.StringArguments["user"]));
            else
            {
                this.ParentBot.SendBroadcastMessageFromBot(string.Format("Banning '{0}' for {1} seconds.", message.StringArguments["user"], message.StringArguments["duration"]));
                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString(System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern));
                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToUniversalTime().ToString(System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern));
                TimeSpan ts = TimeSpan.FromSeconds(Convert.ToInt32(duration));
                System.Diagnostics.Debug.WriteLine(ts.TotalSeconds);
                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToUniversalTime().AddSeconds(ts.TotalSeconds).ToLocalTime().ToString(System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern));
            }

            // should be sending a STA here...
            //nodeToBan.Connection.DisconnectNode();
            return true;
        }
    }
}
